from dailyspents.model.Spent import Spent
from dailyspents.controller.CategoryController import CategoryController
from dailyspents.controller.SpentController import SpentController
from dailyspents.controller.PaymentController import PaymentController
from dailyspents.model.Category import Category
from dailyspents.model.Payment import Payment

def importCSV(filePath, user):
    
    categoryController = CategoryController(user)
    paymentController = PaymentController(user)
    spentController = SpentController(user)

    spents = []
    categories = {}
    payments = {}
    
    csvFile = open(filePath, 'r')
    
    for num, line in enumerate(csvFile.readlines()):
        print num
        splitedLine = line.split(',')
        
        cat = Category()
        cat.name = splitedLine[1].replace('\n', '')
        cat.user = user
        
        payment = Payment()
        payment.name = splitedLine[3].replace('\n', '')
        payment.user = user
        
        spent = Spent()
        spent.user = user
        
        spent.date = splitedLine[0].replace('\n', '')
        try:
            spent.description = splitedLine[4].replace('\n', '')
        except Exception, e:
            spent.description = None
            
        spent.value = eval(splitedLine[2].replace('\n', ''))
        spent.category = cat
        spent.payment = payment
        
        categories[spent.category.name] = spent.category
        payments[spent.payment.name] = spent.payment
        
        spents.append(spent)
    
    csvFile.close()
    
    print categories
    print payments
    
    for k, v in categories.items():
        try:
            print k
            print v
            categoryController.save(v)
            print '>>> gravando categoria', k
        except Exception, e:
            raise e
        
    for k, v in payments.items():
        try:
            print v
            print k
            paymentController.save(v)
            print '>>> gravando payment', k
        except Exception, e:
            print e
            pass
    
    for spent in spents:
        spent.category = categoryController.getByName(spent.category.name)
        spent.payment = paymentController.getByName(spent.payment.name)
        
        try:
            spentController.save(spent)
        except Exception, e:
            print e
            pass